package streaming.demo;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import utils.PropertiesReader;

/**
 *
 */
public class Socket2WCDemo1 {

    private static String socketIP = PropertiesReader.get("default.socket.ip");
    private static Integer socketPort = PropertiesReader.getInteger("default.socket.port");

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        env.setParallelism(1);

        String delimiter = "\n";
        long twSize = 2L;//时间窗口大小,单位s
        long twInterval = 1L;//指定时间间隔,单位s

        DataStream<String> inputStream = env.socketTextStream(socketIP, socketPort, delimiter);
        DataStream<WordWithCount> dataStream = inputStream.flatMap(new FlatMapFunction<String, WordWithCount>() {
            @Override
            public void flatMap(String s, Collector<WordWithCount> out) throws Exception {
                String[] splits = s.split("\\s");//分隔符 空格
                for (String word : splits) {
                    out.collect(new WordWithCount(word, 1L));
                }
            }
        })
        .keyBy("word")
//        .timeWindow(Time.seconds(twSize), Time.seconds(twInterval))
        .reduce(new ReduceFunction<WordWithCount>() {
            @Override
            public WordWithCount reduce(WordWithCount w1, WordWithCount w2) throws Exception {
                return new WordWithCount(w1.word, w1.count + w2.count);
            }
        });
        dataStream.print();
        env.execute("Socket2WCDemo1");
    }

    public static class WordWithCount {
        public String word;
        public Long count;

        public WordWithCount() {}

        public WordWithCount(String word, Long count) {
            this.word = word;
            this.count = count;
        }

        @Override
        public String toString() {
            return "WordWithCount{" +
                    "word='" + word + '\'' +
                    ", count=" + count +
                    '}';
        }
    }

}
